package net.xuele.learn.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yubo
 * @date: 16:50 2020/7/31
 * @Description: 类描述
 */
@Component
public class RedisScript {
    @Autowired
    private RedisTemplate redisTemplate;

    public void execute() {
        List<String> keys = new ArrayList<>();
        keys.add("test_key1");
        List<String> args = new ArrayList<>();
        args.add("hello,key1");
        String LUA = "redis.call('SET', KEYS[1], ARGV[1]); return ARGV[1]";

        //spring自带的执行脚本方法中，集群模式直接抛出不支持执行脚本异常，此处拿到原redis的connection执行脚本
        String result = (String) redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {

                Object nativeConnection = redisConnection.getNativeConnection();

                if (nativeConnection instanceof JedisCluster) {
                    // 集群
                    return (String) ((JedisCluster) nativeConnection).eval(LUA, keys, args);
                } else if (nativeConnection instanceof Jedis) {
                    // 单点
                    return (String) ((Jedis) nativeConnection).eval(LUA, keys, args);
                }

                return null;
            }
        });
        System.out.println(result);
    }
}
